let log4js = require('log4js');
 log4js.configure({
    appenders: {fileout: { type: "file", filename: "./logs/event.log" },consoleout: { type: "console" }},
    categories: {default: { appenders: ["fileout","consoleout"], level: "info" }}
})
let log = log4js.getLogger("event");
log.level = "info"; // default level is OFF - which means no logs at all.


const ethers = require("ethers");
const dayjs = require("dayjs");
const db = require("./common/mysql");
const redis = require("./common/redis").redis;
const config = require("./common/config").config;

// WebSocket
const wsProviderUrl = config.wsProviderUrl; 
const provider = new ethers.WebSocketProvider(wsProviderUrl);
const contractAddress = config.contractAddress;
const contractAbi = require("./abi.json");
const contract = new ethers.Contract(contractAddress, contractAbi, provider);

// emit Buy(owner, msgValue, block.timestamp, orderIndex);
contract.on("Buy", (buyer,buyValue,buyTime,orderIndex) => {
    let buyTimeFmt=dayjs(buyTime*1000).format('YYYY-MM-DD HH:mm:ss');
    const buyValueFmt = ethers.formatUnits(buyValue, 18); 
    log.info(`Buy detected: buyer: ${buyer}, buyValue: ${buyValueFmt}, buyTime: ${buyTimeFmt}, orderIndex: ${orderIndex}`)
    const data={
        buyer:buyer,
        buyValue:buyValue,
        buyTime:buyTime,
        orderIndex:orderIndex
    };
    saveBuy(data);
});


// // 使用原生 WebSocket 事件处理
// const ws = provider._websocket;

// ws.onopen = () => {
//     console.log("WebSocket connection established.");
// };

// ws.onclose = () => {
//     console.log("WebSocket connection closed.");
// };

// ws.onerror = (error) => {
//     console.error("WebSocket error:", error);
// };

const saveBuy=(data)=>{
    parse(data);
    log.info("Save buy: ",data);
    
    // INSERT INTO `uzi`.`app_buy` (`id`, `buyer`, `buy_value`, `buy_time`, `order_index`,   `reward_count`, `reward_balance`, `reward_time`, `reward_next_time`, `market_count`, `market_balance`, `market_time`, `market_next_time`, `create_time`, `update_time`) VALUES (1, '0x81828932845D4B38C5C5af2e856e8e34c54d1f1D', '1500000000000000', '1735844015', 3, '0.0015', '2025-01-03 02:53:35', 0, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL, '2025-01-03 10:40:00', '2025-01-03 10:40:00');

    const sql = "INSERT INTO `uzi`.`app_buy` (`buyer`, `buy_value`, `buy_time`, `order_index`,  `reward_count`, `reward_balance`, `reward_time`, `reward_next_time`, `market_count`, `market_balance`, `market_time`, `market_next_time`, `create_time`, `update_time`) VALUES "
    +`('${data.buyer}', ${data.buyValue}, '${data.buyTime}', ${data.orderIndex}, ${data.rewardCount},${data.rewardBalance},null,'${data.rewardNextTime}',${data.marketCount},${data.marketBalance},null,'${data.marketNextTime}', now(), now());`;

    if(!data.buyer){
        return;
    }

    const id=`${data.buyer}-${data.buyValue}-${data.buyTime}`;

    db.query(sql, (error, results) => {
        if(error){
            // 创建失败
            log.error("save buy error: \n",error);
            log.error("save buy error: \n",sql);
        } else {
            // 创建成功
            log.info(`save buy ${id} successfully`)
            pubBuy(data);
        }
    })
}

const parse=(data) => {
    const buyTimeFmt=dayjs(data.buyTime*1000).format('YYYY-MM-DD HH:mm:ss');
    data.buyTime=buyTimeFmt;
    
    const buyValueFmt = ethers.formatUnits(data.buyValue, 18); 
    data.buyValue=buyValueFmt;

    data.rewardCount=config.changeTotal;
    data.rewardBalance=data.buyValue;
    data.rewardNextTime=dayjs(buyTimeFmt).add(config.changeDelay,'hour').format('YYYY-MM-DD HH:mm:ss');
    
    data.marketCount=config.changeTotal;
    data.marketBalance=data.buyValue;
    data.marketNextTime=dayjs(buyTimeFmt).add(config.changeDelay,'hour').format('YYYY-MM-DD HH:mm:ss');
}


const pubBuy=(data)=>{
    const channel = 'event-buy';
    log.info(`publish channel: ${channel} message: ${JSON.stringify(data)}`);
    redis.publish(channel, JSON.stringify(data));
}


log.info("Listening for Buy events...");

// test
// owner: 0x81828932845D4B38C5C5af2e856e8e34c54d1f1D
// msgValue: 1500000000000000
// timestamp: 1735844015
// orderIndex: 3
const data={
    buyer:'0x81828932845D4B38C5C5af2e856e8e34c54d1f1D',
    buyValue:'1500000000000000',
    buyTime:1735844015,
    orderIndex:3
};

getEvents();

// saveBuy(data);
// pubBuy(data);




